import easyocr
import numpy as np
from PIL import Image

from process.chooseCharacter import getpot


def crop_image(image, box):
    """
    根据矩形框裁剪图像。

    :param image: PIL 图像对象
    :param box: 矩形框坐标列表 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
    :return: 裁剪后的 PIL 图像对象
    """
    # 确保 box 是一个包含四个坐标点的列表
    if not isinstance(box, list) or len(box) != 4 or not all(isinstance(p, (list, tuple)) and len(p) == 2 for p in box):
        raise ValueError("box 参数应为包含四个点的列表，每个点是一个 [x, y] 列表或元组")

    # 获取矩形框的最小和最大坐标
    min_x = min(p[0] for p in box)
    max_x = max(p[0] for p in box)
    min_y = min(p[1] for p in box)
    max_y = max(p[1] for p in box)

    # 确保坐标在图像范围内
    min_x = max(min_x, 0)
    min_y = max(min_y, 0)
    max_x = min(max_x, image.width)
    max_y = min(max_y, image.height)

    # 裁剪图像
    cropped_image = image.crop((min_x, min_y, max_x, max_y))
    return cropped_image


def find_text_location_easyocr(image, box):
    """
    从图像中的指定区域提取文字信息。

    :param image_path: 图像文件路径
    :param box: 矩形框坐标列表 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
    :return: 识别的文字信息列表
    """
    # 初始化 EasyOCR 读者，指定中文语言模型
    reader = easyocr.Reader(['ch_sim', 'en'])  # 中文简体 + 英文

    # # 打开图像文件
    # try:
    #     image = Image.open(image_path)
    # except Exception as e:
    #     raise FileNotFoundError(f"无法打开图像文件：{e}")
    # 将截图转换为 NumPy 数组
    image = Image.fromarray(np.array(image))
    # 裁剪指定区域
    cropped_image = crop_image(image, box)

    # 将 PIL 图像对象转换为 NumPy 数组
    image_np = np.array(cropped_image)

    # 使用 EasyOCR 提取文字信息
    results = reader.readtext(image_np)

    return results


def pl(pot):
    # x=pot[0].top_left[0]
    # y=pot[0].top_left[1]
    w = pot[0].bottom_right[0] - pot[0].top_left[0]
    h = pot[0].bottom_right[1] - pot[0].top_left[1]
    x = pot[0].bottom_right[0]
    y = pot[0].bottom_right[1]
    # print(f"w={w},h={h}")
    # print(pot[0].top_left, pot[0].bottom_right)
    offset_x = w * 28.5
    offset_y = h + h / 3
    # click_icons(int(x+w), int(y-h))
    return [[x, y - h], [x + w, y - h], [x + w, y],
            [x, y]]


def get_plz() -> int:
    p4, img = getpot(['./tasks/icos/plz.png'])
    if len(p4) > 0:
        box = pl(p4)
        print(f"box={box}")
        # 定义矩形框的四个点坐标 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
        # 你需要根据实际图像坐标调整这些值
        # box = [[50, 50], [200, 50], [200, 150], [50, 150]]
        try:
            results = find_text_location_easyocr(img, box)
            for result in results:
                # result[0] 是文本位置的边界框，result[1] 是识别的文本，result[2] 是置信度
                box, text, confidence = result
                plz = int(text[:-4])
                return plz
                # print(f"Text: {plz}")
                # print(f"Confidence: {confidence}")
                # print(f"Bounding Box: {box}")
        except Exception as e:
            print(f"发生错误：{e}")


if __name__ == "__main__":
    # main()
    pass
